/*
* 设备维护填报
* */

import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:center_beijing/widgets/imageSelect_widget.dart';
import 'package:center_beijing/widgets/textarea_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:images_picker/images_picker.dart';
import 'package:left_scroll_actions/cupertinoLeftScroll.dart';
import 'package:left_scroll_actions/global/actionListener.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'dart:io';
import 'dart:convert';
import 'package:center_beijing/common/QRScan.dart';
import 'package:http_parser/http_parser.dart';
class EquipmentProblemReport extends StatefulWidget {
  @override
  _EquipmentProblemReportState createState() => _EquipmentProblemReportState();
}

class _EquipmentProblemReportState extends State<EquipmentProblemReport>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  final TextEditingController problemDescription =
      TextEditingController(); //问题描述
  var equipment = Get.arguments;
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  List selectList = [];
  List<SelectItems> typeList = [
    // SelectItems(label: "维修", value: '1'),
    SelectItems(label: "保养", value: '2'),
    // SelectItems(label: "巡检", value: '3'),
    // SelectItems(label: "检定", value: '4'),
    // SelectItems(label: "鉴定", value: '5'),
    SelectItems(label: "小修", value: '6'),
  ];
  SelectItems selectType = SelectItems();
  List<Media> photos = [];
  List passPhoto = [];
  String remark = '';
  ImageForm.FormData formData;

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
    var bbq = GlobalConfig.userInfo;
    if(equipment!=null){
      this.setState(() {
        selectList.add(equipment);
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }


  getEquipmentDetail(compId) async {
    var pass = {
      'id':compId
    };
    var result = await getEquipmentInfo(pass);
    if (result != null&& result['errorMessage'] == null) {
      selectList = [];
      this.setState(() {
        selectList.add(result);
      });
    }
  }

  justifyInfo() {
    if (selectList.length == 0) {
      Fluttertoast.showToast(msg: '请选择设备');
      return false;
    } else if (selectType.value == null) {
      Fluttertoast.showToast(msg: '请选择类型');
      return false;
    } else {
      return true;
    }
  }

/*
  * 提交
  * */
  submit() async {
    var pass = {
      'item': json.encode({
        'machineName': selectList[0]['name'],
        'maintenanceType': selectType.value,
        'maintenanceDate': Utils.timeUtil(DateTime.now().toIso8601String()),
        'operator': GlobalConfig.userInfo['employeeId'],
        'personInCharge':GlobalConfig.userInfo['employeeId'],
        'maintenanceContent': remark,
        'machineId': selectList[0]['id']
      }),
      'fileList': json.encode(this.passPhoto),
    };
    var result = await saveEquipmentRecord(pass);
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '提交完成');
      Go.Get.back();
    }
  }

  Future addImage() async {
    this.passPhoto = [];
    loading.show(delay: 10);
    if (this.photos.length > 0) {
      var temPhotos = [];
      temPhotos.addAll(this.photos);
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < temPhotos.length; i++) {
        Media asset = temPhotos[i];
        File file = File(asset.path);
        formData.files.add(MapEntry("files",
            await ImageForm.MultipartFile.fromFile(file.path.toString(),contentType: MediaType('image',file.path.toString().split('.').last))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        this.passPhoto = [];
        result.forEach((item) {
          this.passPhoto.add({
            'fileId': item['attachmentId'],
            'fileName': item['fileName'],
            'fileType': item['fileName'].split('.').last
          });
        });
        LogUtil.d(this.passPhoto);
        this.submit();
      }
    } else {
      this.submit();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('设备维护填报'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child: SingleChildScrollView(
            child: GestureDetector(
              onTap: (){
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: Column(
                children: [
                  equipment!=null?Container():Container(
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing16, 0, Styles.spacing16, 0),
                    margin: EdgeInsets.fromLTRB(
                        0, Styles.spacing8, 0, Styles.spacing8),
                    child: Row(
                      children: [
                        Expanded(
                          child: GestureDetector(
                            onTap: () async {
                              var result =
                              await Get.toNamed(RouteConfig.selectEquipment);
                              if (result != null) {
                                selectList = [];
                                selectList.add(result);
                              }
                            },
                            child: Container(
                              alignment: Alignment.center,
                              padding: EdgeInsets.fromLTRB(
                                  Styles.spacing16,
                                  Styles.spacing8,
                                  Styles.spacing16,
                                  Styles.spacing8),
                              decoration: BoxDecoration(
                                  color: Styles.GrayLight,
                                  border: Border.all(
                                      color: Styles.LineColor, width: 1),
                                  borderRadius:
                                  BorderRadius.all(Radius.circular(4.0.r))),
                              child: Text(
                                '搜索/手动选择设备',
                                style: TextStyle(
                                    color: Styles.LeftTitleColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () async {
                            var result = await QrScan.scan(context,type: 2);
                            if(result!=null){
                              this.getEquipmentDetail(result['code']);
                            }
                          },
                          child: Container(
                            color: Styles.BlueColor,
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing8,
                                Styles.spacing8,
                                Styles.spacing8,
                                Styles.spacing8),
                            margin: EdgeInsets.only(left: Styles.spacing16),
                            child: Image.asset(
                              'assets/images/scan.png',
                              width: 20.w,
                              height: 20.h,
                              fit: BoxFit.contain,
                              color: Colors.white,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Column(
                    children: this.selectList.map((item) {
                      return CupertinoLeftScroll(
                        // important, each Row must have different key.
                        // DO NOT use '$index' as Key! Use id or title.
                        key: Key(item.toString()),
                        // left scroll widget will auto close while the other widget is opened and has same closeTag.
                        // 当另一个有相同closeTag的组件打开时，其他有着相同closeTag的组件会自动关闭.
                        closeTag: LeftScrollCloseTag(item.toString()),
                        buttonWidth: 80,
                        child: Container(
                          color: Colors.white,
                          padding: EdgeInsets.fromLTRB(Styles.spacing8,
                              Styles.spacing8, Styles.spacing8, Styles.spacing8),
                          margin: EdgeInsets.only(top: Styles.spacing8),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Container(
                                    margin:
                                    EdgeInsets.only(right: Styles.spacing8),
                                    height: 20.h,
                                    width: 4.w,
                                    color: Styles.BlueColor,
                                  ),
                                  Text(
                                    item['name'] != null ? item['name'] : (item['equipmentName']!=null?item['equipmentName']:'--'),
                                    style: TextStyle(
                                        color: Styles.DetailColor,
                                        fontSize: Styles.Middle16Font),
                                  ),
                                ],
                              ),
                              Container(
                                margin: EdgeInsets.fromLTRB(Styles.spacing8,
                                    Styles.spacing8, Styles.spacing8, 0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      (item['attr'] != null &&
                                          item['attr']['modelType'] != null)
                                          ? item['attr']['modelType']
                                          : (item['modelType'] != null ? item['modelType'] : '--'),
                                      style: TextStyle(
                                          color: Styles.DetailColor,
                                          fontSize: Styles.Middle16Font),
                                    ),
                                    Text(
                                      (item['attr'] != null &&
                                          item['attr']['address'] != null)
                                          ? item['attr']['address']
                                          : (item['address'] != null ? item['address'] : '--'),
                                      style: TextStyle(
                                          color: Styles.LeftTitleColor,
                                          fontSize: Styles.NormalFont),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        buttons: <Widget>[
                          GestureDetector(
                            onTap: () {
                              print('删除');
                            },
                            child: Container(
                              margin:
                              EdgeInsets.fromLTRB(0, 0, Styles.spacing16, 0),
                              decoration: BoxDecoration(
                                color: Styles.RedColor,
                                borderRadius:
                                BorderRadius.all(Radius.circular(14.0.r)),
                              ),
                              alignment: Alignment.center,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image(
                                    image: AssetImage('assets/images/delete.png'),
                                    width: 16.w,
                                    height: 16.w,
                                    fit: BoxFit.contain,
                                  ),
                                  Text(
                                    '删除',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: Styles.NormalFont),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ],
                        onTap: () {
                          print('tap row');
                        },
                      );
                    }).toList(),
                  ),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    child: CustomSelectWidget(
                      require: true,
                      rightText:
                      selectType.label != null ? selectType.label : '请选择',
                      items: typeList,
                      selectCallback: (value) => this.setState(() {
                        selectType = value;
                      }),
                      title: '问题类型',
                    ),
                  ),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(
                        Styles.spacing8, 0, Styles.spacing8, 0),
                    child: TextAreaWidget(
                      maxLength: 100,
                      textController: problemDescription,
                      labelText: '问题描述',
                      defaultValue: '',
                      placeholder: '请输入',
                      disabled: false,
                      required: false,
                      rows: 4,
                      onChange: (value) => this.setState(() {
                        remark = value;
                      }),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    color: Colors.white,
                    child: Column(
                      children: [
                        Padding(
                          padding: EdgeInsets.fromLTRB(
                              Styles.spacing16, Styles.spacing8, 0, 0),
                          child: Row(
                            children: <Widget>[
                              Text(
                                '现场照片(${this.photos.length}/6)',
                                style: TextStyle(
                                    color: Styles.DetailColor,
                                    fontSize: Styles.MiddleFont17),
                              ),
                            ],
                          ),
                        ),
                        ImageSelectWidget(
                          onchange: (value) {
                            this.setState(() {
                              photos = value;
                            });
                          },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                if (this.justifyInfo()) {
                  showDialog(
                      barrierDismissible: false,
                      context: this.context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('注意'),
                          content: Text('确认提交吗？'),
                          actions: <Widget>[
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "取消",
                                  style: TextStyle(color: Colors.black),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ),
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "确定",
                                  style: TextStyle(color: Colors.red),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                  this.addImage();
                                },
                              ),
                            ),
                          ],
                        );
                      });
                }
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
